package com.mf.page.menu;

import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.mf.MyApplication;
import com.mf.page.Actions;
import com.mf.page.menu.MainMenuFunc.OnClickMenuListener;
import com.mf.mpos.pub.Controler;

/*
 * 将按键消息放到线程里面异步处理，避免弹出界面显示不出来等问题
 */
public class MainMenuClickedRunnable implements Runnable{
	private static MainMenuClickedRunnable  instance = null;
	Handler mHandler;
	
	public static MainMenuClickedRunnable Instance(){
		if(instance == null){
			instance = new MainMenuClickedRunnable();
		}
		return instance;
	}
	
	public MainMenuClickedRunnable() {
		// TODO Auto-generated constructor stub
		new Thread(this).start();
	}
	
	public void MenuClicked(HashMap<String,Object> map)
	{
		Message msg = new Message();
		msg.obj = map;
		
		if(mHandler != null)
		{
			Log.v("uninpay", "before sendMessage");
			mHandler.sendMessage(msg);
		}
		
	}
	
	@SuppressLint("HandlerLeak")
	@Override
	public void run() {
		// TODO Auto-generated method stub
	    Looper.prepare();
	    
	    mHandler = new Handler() {	
	    	
            public void handleMessage(Message msg) {            	
                // process incoming messages here
            	Log.v("uninpay", "handle sendMessage");
            	if(msg.obj != null)
            	{
            		HashMap<String,Object> map = (HashMap<String,Object>)msg.obj;
            		String id = map.get("id").toString();
            		String title = map.get("title").toString();
            		Activity activity = (Activity)map.get("activity");
            		
            		ArrayList<OnClickMenuListener> dealfuncList = MainMenuFunc.Instance().getMenuDealFuncList();
            		//若有菜单预处理回调，执行菜单回调
            		for(int i = 0; i< dealfuncList.size(); i ++){
            			OnClickMenuListener OnClick1 = dealfuncList.get(i);
            			int ret = OnClick1.OnClick(activity,id, title);
            			if(ret != 0){
            				break;
            			}
            		}
            		//菜单处理完，断开蓝牙和关闭通讯提示界面
            //		BluetoothControler.disconnectPos(MyApplication.getInstance().getApplicationContext());
        			Actions.CloseMsg();
            	}
            	
            }
        };

        Looper.loop();
	}
}
